package leetcode.code2376;

import java.util.HashSet;
import java.util.Set;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	int len;
	int nums[];

	public int countSpecialNumbers(int n) {
		String num = String.valueOf(n);
		len = num.length();
		nums = new int[num.length()];
		int p = len - 1;
		while (n > 0) {
			nums[p--] = n % 10;
			n /= 10;
		}
		Integer[][] dp = new Integer[len][1 << 10];
		return this.countSpecialNumbers(0, 0, true, dp);
	}

	private int countSpecialNumbers(int index, int used, boolean max, Integer[][] dp) {
		if (index == len) {
			return used == 0 ? 0 : 1;
		}
		if (dp[index][used] != null && !max) {// && !max
			return dp[index][used];
		}
		int ans = 0;
		if (used == 0) {
			ans += this.countSpecialNumbers(index + 1, used, false, dp);
		}
		int from = used == 0 ? 1 : 0;
		int to = max ? nums[index] : 9;
		for (int i = from; i <= to; i++) {
			if ((used >> i & 1) == 0)
				ans += this.countSpecialNumbers(index + 1, used | (1 << i), max && i == nums[index], dp);
		}
		dp[index][used] = ans;
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(243, this.countSpecialNumbers(310));
		H.compare(252, this.countSpecialNumbers(321));
		H.compare(505954, this.countSpecialNumbers(6517414));
		H.compare(19, this.countSpecialNumbers(20));
		H.compare(740, this.countSpecialNumbers(1024));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
		int num = 0;
		num|=1<<5;
		num|=1<<3;
		num|=1<<2;
		System.out.println(Integer.toBinaryString(num));
	}

}
